/**
 * 菜单管理模块
 */
const router = require('koa-router')();
const jwt = require('../utils/jwt');
const menuDB = require('../models/menuSchema');
const util = require('../utils/util');
const md5 = require('md5');
router.prefix('/menu');

// 查询菜单列表
router.get('/list', async (ctx) => {
  let { menuName, menuState } = ctx.request.query;
  let params = {};
  if (menuName) params.menuName = menuName;
  if (menuState) params.menuState = menuState;
  let menuList = (await menuDB.find(params)) || [];
  let list = util.getTreeMenu(menuList, null, []);
  ctx.body = util.success(list);
});

// 编辑或添加菜单
router.post('/operate', async (ctx) => {
  let { _id, action, ...params } = ctx.request.body;
  let res, info;

  try {
    if (action === 'add') {
      res = await menuDB.create(params);
      info = '添加成功';
    } else if (action === 'edit') {
      params.updateTime = new Date();
      res = await menuDB.updateOne({ _id }, params);
      info = '编辑成功';
    } else if (action === 'delete') {
      info = '删除成功';
      res = await menuDB.findByIdAndRemove({ _id });
      // _id 在 parentId 数组中的都要删除
      res = await menuDB.deleteMany({ parentId: { $all: [_id] } });
    } else {
      ctx.body = util.fail();
    }
    ctx.body = util.success({}, info);
  } catch (err) {
    ctx.body = util.fail();
  }
});

module.exports = router;
